package com.ccloud.auth.modules.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.ccloud.api.system.domain.SysRole;
import com.ccloud.api.system.domain.SysUser;
import com.ccloud.api.system.domain.SysUserRole;
import com.ccloud.api.system.service.ISysRoleService;
import com.ccloud.api.system.service.ISysUserRoleService;
import com.ccloud.api.system.service.ISysUserService;
import com.ccloud.auth.common.model.Oauth2Constant;
import com.ccloud.auth.common.model.SecurityUser;
import com.ccloud.common.core.utils.ValueUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author chentailai
 * UserDetailsService的实现类，从数据库加载用户的信息，比如密码、角色。。。。
 */
@Service
@Primary
public class JwtTokenUserDetailsService implements UserDetailsService {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private ISysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getUserByName(username);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        //角色
        List<SysUserRole> sysUserRoles = sysUserRoleService.findByUserId(ValueUtils.parseLong(user.getId()));
        //该用户的所有权限（角色）
        List<String> roles = new ArrayList<>();
        for (SysUserRole userRole : sysUserRoles) {

            SysRole sysRoleDb = sysRoleService.getById(userRole.getRoleId());
            if (!Objects.isNull(sysRoleDb)) {
                roles.add(Oauth2Constant.ROLE_PREFIX + sysRoleDb.getRoleCode());
            }
        }
        return SecurityUser.builder()
                .userId(ValueUtils.parseString(user.getId()))
                .username(user.getUsername())
                .password(user.getPassword())
                //将角色放入authorities中
                .authorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles, String.class)))
                .build();
    }
}
